package com.example.zwh.computershop.handleDataClient;

import com.example.zwh.computershop.sqlModel.User;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class JsonUtil {
	//将对象添加到HashMap并转化为josn字符串
	public static String hashMapToJson(HashMap<String, Object> params) {
		JSONObject jsonObject = JSONObject.fromObject(params);//java对象变成json对象
		String jsonStr = jsonObject.toString();//json对象转换成json字符串
		return jsonStr;
	}
	
	//获取josn字符串里的数据并转化为对象
	public static Object getObject(JSONObject josnObject, String name) {
		//获取要转的对象数据
		String str = josnObject.getString(name);
		
		JSONObject obj = new JSONObject().fromObject(str);
		return getUser(obj);
	}
	
	//获取相应的对象
	
	public static Object getUser(JSONObject obj) {
		return (Object)JSONObject.toBean(obj, User.class);
	}
	
	public static String getWebTxt(String url) {
        URL u;
        HttpURLConnection httpURLConnection;
        String ret = "";
        try {
        	
            u = new URL(url);
            httpURLConnection = (HttpURLConnection)u.openConnection();
            
            if (httpURLConnection.getResponseCode() == 200) {
            	
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));

                String read;
                while ((read = bufferedReader.readLine()) != null) {
                    ret += read ;
                    ret += "\r\n" ;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        	System.out.println("解析网页错误!");
        	return "f";
        }
        return ret ;
    }
}
